<?php
/**
*
* @package install
* @version $Id: install_install.php 8479 2008-03-29 00:22:48Z naderman $
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
*/
if (!defined('IN_INSTALL'))
{
	// Someone has tried to access the file direct. This is not a good idea, so exit
	exit;
}

if (!empty($setmodules))
{
	// If phpBB is already installed we do not include this module
	if (@file_exists($phpbb_root_path . 'config.' . $phpEx))
	{
		include_once($phpbb_root_path . 'config.' . $phpEx);

		if (!defined('PHPBB_INSTALLED'))
		{
			return;
		}
	}

	$module[] = array(
		'module_type'		=> 'install',
		'module_title'		=> 'INSTALL',
		'module_filename'	=> substr(basename(__FILE__), 0, -strlen($phpEx)-1),
		'module_order'		=> 10,
		'module_subs'		=> '',
		//All Steps in the right order
		'module_stages'		=> array('INTRO', 'REQUIREMENTS', 'ADVANCED', 'CREATE_TABLE', 'FINAL'),
		'module_reqs'		=> ''
	);
}

/**
* Installation
* @package install
*/
class install_install extends module
{

	function install_install(&$p_master)
	{
		$this->p_master = &$p_master;
	}

	function main($mode, $sub)
	{
		global $user, $template, $useruage, $phpbb_root_path, $phpEx;
        //What is to do by which step?
		switch ($sub)
		{
			case 'intro':
				$this->page_title = $user->lang['SUB_INTRO'];

				$template->assign_vars(array(
					'TITLE'			=> $user->lang['INSTALL_INTRO'],
					'BODY'			=> $user->lang['INSTALL_INTRO_BODY'],
					'L_SUBMIT'		=> $user->lang['NEXT_STEP'],

					'U_ACTION'		=> append_sid($this->p_master->module_url . "?mode=$mode&amp;sub=requirements"),
				));

			break;

			case 'requirements':
				$this->check_server_requirements($mode, $sub);
			break;

			case 'create_table':
				$this->load_schema($mode, $sub);
				include($phpbb_root_path . 'includes/acp/auth.' . $phpEx);
                $auth_admin = new auth_admin();

                // Add foo permissions as local permissions
                // (you could instead make them global permissions by making the obvious changes below)
                $auth_admin->acl_add_option(array(
                    'local'        => array('f_click_link_extern', 'f_click_link_intern'),
                    'global'    => array('u_click_link_extern', 'u_click_link_intern', 'u_see_real_link')
                ));
			break;

			case 'advanced':
				$this->obtain_advanced_settings($mode, $sub);

			break;

			case 'final':
				$this->page_title = $user->lang['SUB_FINAL'];

				$template->assign_vars(array(
					'TITLE'			=> $user->lang['INSTALL_FINAL'],
					'BODY'			=> $user->lang['INSTALL_FINAL_BODY'],
					'L_SUBMIT'		=> $user->lang['FINAL_STEP'],

					'U_ACTION'		=> append_sid("{$phpbb_root_path}index.$phpEx"),

				));

				// Remove the lock file
				@unlink($phpbb_root_path . 'cache/install_lock');

			break;
		}

		$this->tpl_name = 'install_install';
	}

	/**
	* Checks that the server we are installing on meets the requirements for running phpBB
	*/
	function check_server_requirements($mode, $sub)
	{
		global $user, $template, $phpbb_root_path, $phpEx, $useruage, $dbms, $board_config;
		$this->page_title = $user->lang['STAGE_REQUIREMENTS'];

		$template->assign_vars(array(
			'TITLE'		=> $user->lang['REQUIREMENTS_TITLE'],
			'BODY'		=> $user->lang['REQUIREMENTS_EXPLAIN'],
		));

		$passed = array('files' => false);
		// Test for basic PHP settings

		$imagick_needed = false;

        if(sizeof($this->php_dlls_other) > 0 || $imagick_needed)
        {
    		// Test for other modules
    		$template->assign_block_vars('checks', array(
    			'S_LEGEND'			=> true,
    			'LEGEND'			=> $user->lang['PHP_OPTIONAL_MODULE'],
    			'LEGEND_EXPLAIN'	=> $user->lang['PHP_OPTIONAL_MODULE_EXPLAIN'],
    		));

    		foreach ($this->php_dlls_other as $dll)
    		{
    			if (!@extension_loaded($dll))
    			{
    				if (!can_load_dll($dll))
    				{
    					$template->assign_block_vars('checks', array(
    						'TITLE'		=> $user->lang['DLL_' . strtoupper($dll)],
    						'RESULT'	=> '<strong style="color:red">' . $user->lang['UNAVAILABLE'] . '</strong>',

    						'S_EXPLAIN'	=> false,
    						'S_LEGEND'	=> false,
    					));
    					continue;
    				}
    			}

    			$template->assign_block_vars('checks', array(
    				'TITLE'		=> $user->lang['DLL_' . strtoupper($dll)],
    				'RESULT'	=> '<strong style="color:green">' . $user->lang['AVAILABLE'] . '</strong>',

    				'S_EXPLAIN'	=> false,
    				'S_LEGEND'	=> false,
    			));
    		}
        }
		// Check permissions on files/directories we need access to
		$template->assign_block_vars('checks', array(
			'S_LEGEND'			=> true,
			'LEGEND'			=> $user->lang['FILES_REQUIRED'],
			'LEGEND_EXPLAIN'	=> $user->lang['FILES_REQUIRED_EXPLAIN'],
		));

		//All uploaded files and dirs can be checked, so we can stop some "only run Files in the Browser" noobs ;)

		$available_dbms = get_available_dbms($dbms);
		if (!isset($available_dbms[$dbms]))
    	{
    		// Someone's been silly and tried providing a non-existant dbms
    		$this->p_master->redirect("index.$phpEx?mode=install");
    	}
    	$schema_file = 'schemas/_' . $available_dbms[$dbms]['SCHEMA'] . '_schema.sql';
    	$schema_file = str_replace('_41', '', $schema_file);
    	$languages = array('en', 'en');

    	$directories = array('link.' . $phpEx, 'includes/functions_link.' . $phpEx, 'install_cryptlink/' . $schema_file);

    	$languages = array();

    	(!in_array($board_config['default_lang'], $languages)) ? ( $languages[] = $board_config['default_lang']) : '';
    	(!in_array($user->lang_name, $languages)) ? ( $languages[] = $user->lang_name) : '';

    	foreach ($languages as $lang)
    	{
    	    $directories[] = 'language/' . $lang . '/mods/info_acp_board.' . $phpEx;
    	    $directories[] = 'language/' . $lang . '/mods/install_crypt_link.' . $phpEx;
    	    $directories[] = 'language/' . $lang . '/mods/link.' . $phpEx;
    	    $directories[] = 'language/' . $lang . '/mods/permissions_link.' . $phpEx;
    	}

    	$passed['files'] = true;;
		foreach ($directories as $dir)
		{
			$write = $exists = true;
			if (file_exists($phpbb_root_path . $dir))
			{
				if (!@is_writable($phpbb_root_path . $dir))
				{
					$write = false;
				}
			}
			else
			{
				$write = $exists = false;
			}
            if($passed['files'] == true)
            {
                $passed['files'] = $write;
            }

			$exists_str = ($exists) ? '<strong style="color:green">' . $user->lang['FOUND'] . '</strong>' : '<strong style="color:red">' . $user->lang['NOT_FOUND'] . '</strong>';

			$template->assign_block_vars('checks', array(
				'TITLE'		=> $dir,
				'RESULT'	=> $exists_str . $write_str,

				'S_EXPLAIN'	=> false,
				'S_LEGEND'	=> false,
			));
		}

		// And finally where do we want to go next (well today is taken isn't it :P)
		$url = (!in_array(false, $passed)) ? $this->p_master->module_url . "?mode=$mode&amp;sub=advanced" : $this->p_master->module_url . "?mode=$mode&amp;sub=requirements&amp";
		$submit = (!in_array(false, $passed)) ? $user->lang['INSTALL_START'] : $user->lang['INSTALL_TEST'];

        $url = append_sid($url);

		$template->assign_vars(array(
			'L_SUBMIT'	=> $submit,
			'S_HIDDEN'	=> $s_hidden_fields,
			'U_ACTION'	=> $url,
		));
	}



	/**
	* Provide an opportunity to customise some advanced settings during the install
	* in case it is necessary for them to be set to access later
	*/
	function obtain_advanced_settings($mode, $sub)
	{
		global $user, $template, $phpEx;

		$this->page_title = $user->lang['MOD_SETTINGS'];
		$template->assign_vars(array(
			'TITLE'		=> $user->lang['MOD_SETTINGS'],
			'BODY'		=> $user->lang['MOD_SETTINGS_EXPLAIN'],
		));
		// Obtain any submitted data
		$data = $this->get_submitted_data();

		$passed = false;

		if (isset($_POST['check']))
		{
			$error = array();

			if (!phpbb_check_hash($data['founder_password'], $user->data['user_password']))
			{
				$error[] = $user->lang['WRONG_PASSWORD'];
			}

			$template->assign_block_vars('checks', array(
				'S_LEGEND'			=> true,
				'LEGEND'			=> $user->lang['STAGE_ADMINISTRATOR'],
				'LEGEND_EXPLAIN'	=> false,
			));

			if (!sizeof($error))
			{
				$passed = true;
				$template->assign_block_vars('checks', array(
					'TITLE'		=> $user->lang['ADMIN_TEST'],
					'RESULT'	=> '<strong style="color:green">' . $user->lang['TESTS_PASSED'] . '</strong>',

					'S_EXPLAIN'	=> false,
					'S_LEGEND'	=> false,
				));
			}
			else
			{
				$template->assign_block_vars('checks', array(
					'TITLE'		=> $user->lang['ADMIN_TEST'],
					'RESULT'	=> '<strong style="color:red">' . implode('<br />', $error) . '</strong>',

					'S_EXPLAIN'	=> false,
					'S_LEGEND'	=> false,
				));
			}
		}

		if (!$passed)
		{
			foreach ($this->mod_settings as $config_key => $vars)
			{
				if (!is_array($vars) && strpos($config_key, 'legend') === false)
				{
					continue;
				}

				if (strpos($config_key, 'legend') !== false)
				{
					$template->assign_block_vars('options', array(
						'S_LEGEND'		=> true,
						'LEGEND'		=> $user->lang[$vars])
					);

					continue;
				}

				$options = isset($vars['options']) ? $vars['options'] : '';

				$template->assign_block_vars('options', array(
					'KEY'			=> $config_key,
					'TITLE'			=> $user->lang[$vars['lang']],
					'S_EXPLAIN'		=> $vars['explain'],
					'S_LEGEND'		=> false,
					'TITLE_EXPLAIN'	=> ($vars['explain']) ? $user->lang[$vars['lang'] . '_EXPLAIN'] : '',
					'CONTENT'		=> $this->p_master->input_field($config_key, $vars['type'], $data[$config_key], $options),
					)
				);
			}
		}
		else
		{
			foreach ($this->mod_settings as $config_key => $vars)
			{
				if (!is_array($vars))
				{
					continue;
				}
				$s_hidden_fields .= '<input type="hidden" name="' . $config_key . '" value="' . $data[$config_key] . '" />';
			}
		}


		$submit = $user->lang['NEXT_STEP'];

		$url = ($passed) ? $this->p_master->module_url . "?mode=$mode&amp;sub=create_table" : $this->p_master->module_url . "?mode=$mode&amp;sub=advanced";
		$s_hidden_fields .= ($passed) ? '' : '<input type="hidden" name="check" value="true" />';

		$template->assign_vars(array(
			'L_SUBMIT'	=> $submit,
			'S_HIDDEN'	=> $s_hidden_fields,
			'U_ACTION'	=> $url,
		));
	}

	/**
	* Load the contents of the schema into the database and then alter it based on what has been input during the installation
	*/
	function load_schema($mode, $sub)
	{
        global $db, $user, $template, $phpbb_root_path, $phpEx, $dbms, $table_prefix;



		$this->page_title = $user->lang['STAGE_CREATE_TABLE'];
		$s_hidden_fields = '';

		// Obtain any submitted data
		$data = $this->get_submitted_data();
		$passed = true;
		$error = array();

		if (!phpbb_check_hash($data['founder_password'], $user->data['user_password']))
		{
		    $passed = false;
            $url = $this->p_master->module_url . "?mode=$mode&amp;sub=advanced";
            $s_hidden_fields .= ($passed) ? '' : '<input type="hidden" name="check" value="true" />';

            $template->assign_vars(array(
                'L_SUBMIT'	=> $submit,
                'S_HIDDEN'	=> $s_hidden_fields,
                'U_ACTION'	=> $url,
                ));

		}

		if($passed == true)
		{
    		$available_dbms = get_available_dbms($dbms);

    		if (!isset($available_dbms[$dbms]))
    		{
    			// Someone's been silly and tried providing a non-existant dbms
    			$this->p_master->redirect("index.$phpEx?mode=install");
    		}
    		// Ok we have the db info go ahead and read in the relevant schema
    		// and work on building the table
    		$dbms_schema = 'schemas/_' . $available_dbms[$dbms]['SCHEMA'] . '_schema.sql';
    		$dbms_schema = str_replace('_41', '', $dbms_schema);

    		// How should we treat this schema?
    		$remove_remarks = $available_dbms[$dbms]['COMMENTS'];
    		$delimiter = $available_dbms[$dbms]['DELIM'];

    		$sql_query = @file_get_contents($dbms_schema);

    		$sql_query = preg_replace('#phpbb_#i', $table_prefix, $sql_query);

    		$remove_remarks($sql_query);

    		$sql_query = split_sql_file($sql_query, $delimiter);

    		foreach ($sql_query as $sql)
    		{
    			//$sql = trim(str_replace('|', ';', $sql));
    			if (!$db->sql_query($sql))
    			{
    				$error = $db->sql_error();
    				$this->p_master->db_error($error['message'], $sql, __LINE__, __FILE__);
    			}
    		}
    		unset($sql_query);

    		// Ok tables have been built, let's fill in the basic information
    		$sql_query = file_get_contents('schemas/schema_data.sql');

    		// Deal with any special comments
    		switch ($dbms)
    		{
    			case 'mssql':
    			case 'mssql_odbc':
    				$sql_query = preg_replace('#\# MSSQL IDENTITY (phpbb_[a-z_]+) (ON|OFF) \##s', 'SET IDENTITY_INSERT \1 \2;', $sql_query);
    			break;

    			case 'postgres':
    				$sql_query = preg_replace('#\# POSTGRES (BEGIN|COMMIT) \##s', '\1; ', $sql_query);
    			break;
    		}

    		// Change prefix
    		$sql_query = preg_replace('#phpbb_#i', $table_prefix, $sql_query);

    		// Change language strings...
    		$sql_query = preg_replace_callback('#\{L_([A-Z0-9\-_]*)\}#s', 'adjust_language_keys_callback', $sql_query);

    		// Since there is only one schema file we know the comment style and are able to remove it directly with remove_remarks
    		remove_remarks($sql_query);
    		$sql_query = split_sql_file($sql_query, ';');

    		foreach ($sql_query as $sql)
    		{
    			//$sql = trim(str_replace('|', ';', $sql));
    			if (!$db->sql_query($sql))
    			{
    				$error = $db->sql_error();
    				$this->p_master->db_error($error['message'], $sql, __LINE__, __FILE__);
    			}
    		}
    		unset($sql_query);

            set_config('enable_cryptlink', $data['enable_cryptlink']);
            set_config('auto_redirect_intern', $data['auto_redirect_intern']);
            set_config('auto_redirect_time_intern', $data['auto_redirect_time_intern']);
            set_config('auto_redirect_extern', $data['auto_redirect_extern']);
            set_config('use_anonymto', $data['use_anonymto']);
            set_config('auto_redirect_time_extern', $data['auto_redirect_time_extern']);
            set_config('collect_link_data', $data['collect_link_data']);
            set_config('enable_hide_link', $data['enable_hide_link']);
            set_config('hide_link_text', $data['hide_link_text']);
            set_config('link_text', $data['hide_link_text']);
            set_config('link_add_id', $data['hide_link_text']);

    		$submit = $user->lang['NEXT_STEP'];

    		$url = append_sid($this->p_master->module_url . "?mode=$mode&amp;sub=final");

    		$template->assign_vars(array(
    			'BODY'		=> $user->lang['STAGE_CREATE_TABLE_EXPLAIN'],
    			'L_SUBMIT'	=> $submit,
    			'S_HIDDEN'	=> build_hidden_fields($data),
    			'U_ACTION'	=> $url,
    		));
		}
	}

    /**
	* Get submitted data
	*/
	function get_submitted_data()
	{
		return array(
			'founder_password'          => request_var('founder_password', ''),

			'enable_cryptlink'          => (bool) request_var('enable_cryptlink', '1'),
            'auto_redirect_extern'      => (bool) request_var('auto_redirect_extern', ''),
            'auto_redirect_intern'      => (bool) request_var('auto_redirect_intern', ''),
            'auto_redirect_time_extern' => (int) request_var('auto_redirect_time_extern', ''),
            'auto_redirect_time_intern' => (int) request_var('auto_redirect_time_intern', ''),
            'use_anonymto'              => (bool) request_var('use_anonymto', ''),
            'quick_bot_redirect'        => (bool)  request_var('quick_bot_redirect', ''),
            'collect_link_data'         => (bool) request_var('collect_link_data', ''),
            'enable_hide_link'          => (bool) request_var('enable_hide_link', ''),
            'hide_link_text'            => request_var('hide_link_text', ''),
            'link_text'                 => request_var('hide_link_text', ''),
            'link_add_id'               => (bool) request_var('hide_link_text', ''),
		);
	}
	var $mod_settings = array(
		'legend1'=> 'CRYPTLINK_CONFIG',

		'enable_cryptlink'			=> array('lang' => 'CRYPTLINK_ACTIV', 'type' => 'radio:enabled_disabled', 'explain' => false),
        'auto_redirect_intern'			=> array('lang' => 'AUTO_REDIRCT_INTERN', 'type' => 'radio:yes_no', 'explain' => true),
        'auto_redirect_time_intern'			=> array('lang' => 'AUTO_REDIRCT_TIME',	'type' => 'text:2', 'explain' => true),
        'auto_redirect_extern'			=> array('lang' => 'AUTO_REDIRCT_EXTERN', 'type' => 'radio:yes_no', 'explain' => true),
        'use_anonymto'			=> array('lang' => 'USE_ANONYMTO', 'type' => 'radio:yes_no', 'explain' => true),
        'auto_redirect_time_extern'			=> array('lang' => 'AUTO_REDIRCT_TIME',	'type' => 'text:2', 'explain' => true),
        'quick_bot_redirect'			=> array('lang' => 'QUICK_BOT_REDIRECT', 'type' => 'radio:yes_no', 'explain' => true),
        'collect_link_data'			=> array('lang' => 'COLLECT_LINK_DATA',	'type' => 'radio:yes_no', 'explain' => true),
        'enable_hide_link'			=> array('lang' => 'ENABLE_HIDE_LINK', 'type' => 'radio:yes_no', 'explain' => true),
        'hide_link_text'			=> array('lang' => 'HIDE_LINK_TEXT', 'type' => 'text: 25:100', 'explain' => true),
        'link_text'			=> array('lang' => 'LINK_TEXT',	'type' => 'text: 25:100', 'explain' => true),
        'link_add_id'			=> array('lang' => 'LINK_ADD_ID', 'type' => 'radio:yes_no', 'explain' => true),

		'legend2'                     => 'PASSWORD_CHECK',
		'founder_password'            => array('lang' => 'FOUNDER_PASSWORD', 'type' => 'password', 'explain' => true),
	);

	/**
	* Specific PHP modules we may require for certain optional or extended features
	*/
	var $php_dlls_other = array();

}

?>